//
//  HomeViewController.m
//  Books
//
//  Created by apple on 12-3-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "HomeViewController.h"
#import "DataService.h"
#import "BookDetailsViewController.h"
#import "BookCityViewController.h"
//#import "DMTools.h"
#import "PushService.h"
@interface HomeViewController ()
@property (weak, nonatomic) IBOutlet UIBarButtonItem *bookDetail;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *bookCity;

@end

@implementation HomeViewController
@synthesize backImage;
@synthesize tableView;
@synthesize tableData;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
     
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    version = [[[UIDevice currentDevice] systemVersion] floatValue];
   
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"shangmian.png"] forBarMetrics:UIBarMetricsDefault];
    
    if ((int)version >6) {
       self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
       
    }else {
    self.bookDetail.tintColor = [UIColor colorWithRed:149.0/255.0 green:98.0/255.0 blue:50.0/255.0 alpha:1];
        self.bookCity.tintColor = [UIColor colorWithRed:149.0/255.0 green:98.0/255.0 blue:50.0/255.0 alpha:1];
        
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
        backItem.title =@"返回";
        [backItem setTintColor:[UIColor colorWithRed:149.0/255.0 green:98.0/255.0 blue:50.0/255.0 alpha:1]];
        
        self.navigationItem.backBarButtonItem = backItem;
    }
    
}
//填充控件
-(void) viewWillAppear:(BOOL)animated
{
     [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    //设置view背景
    NSBundle * mainBundle = [NSBundle mainBundle];
    NSString *coverPath=[mainBundle  pathForAuxiliaryExecutable:@"kongbgiphone.png"];
    
    NSLog(@"%@",coverPath);
    
    UIImage *image =[UIImage imageWithContentsOfFile:coverPath];
  
    self.backImage.image=image;

    if ((int)version <=6) {
        self.backImage.frame = CGRectMake(0, -40, 320, 480);
        self.tableView.frame=CGRectMake(0, 0,  320,416);
    
    }else if(self.view.frame.size.height == 568){
        self.backImage.frame = CGRectMake(0, 20, 320, 548);
      self.tableView.frame=CGRectMake(0, 64,  320,504);
    }else{
        self.backImage.frame = CGRectMake(0, 20, 320, 548);
        self.tableView.frame=CGRectMake(0, 64,  320,414);
    }
    NSMutableDictionary * AppsConfigs =[DataService GetAppsConfigs];
    
    NSLog(@"%@_%@",[AppsConfigs allKeys],[AppsConfigs objectForKey:@"showad"]);
    /*
     if(AppsConfigs!=nil&&[[AppsConfigs objectForKey:@"showad"] intValue]==0)
     {
         if(_dmAdView==nil)
        {
            // 创建广告视图，此处使用的是测试ID，请登陆多盟官网（www.domob.cn）获取新的ID 
            _dmAdView = [[DMAdView alloc] initWithPublisherId:DOMOB_AD_KEY 
                                                     size:DOMOB_AD_SIZE_320x50];
            // 设置广告视图的位置
            _dmAdView.frame = CGRectMake(0, 366, 
                                     DOMOB_AD_SIZE_320x50.width,
                                     DOMOB_AD_SIZE_320x50.height);    
        
            NSLog(@"_dmAdView inited");
        }
         NSLog(@"%@",_dmAdView);
         _dmAdView.delegate = self; // 设置 Delegate
         _dmAdView.rootViewController = self; // 设置 RootViewController
         [self.view addSubview:_dmAdView]; // 将广告视图添加到父视图中
         [_dmAdView loadAd]; // 开始加载广告

         // 检查更新提醒，此处使用的是测试ID，请登陆多盟官网（www.domob.cn）获取新的ID 
         DMTools *_dmTools = [[DMTools alloc] initWithPublisherId:DOMOB_AD_KEY];
         [_dmTools checkRateInfo];
   
     }else{
     
         if(_dmAdView==nil)
         {
             // 创建广告视图，此处使用的是测试ID，请登陆多盟官网（www.domob.cn）获取新的ID 
             _dmAdView = [[DMAdView alloc] initWithPublisherId:DOMOB_AD_KEY 
                                                          size:DOMOB_AD_SIZE_320x50];
             // 设置广告视图的位置
             _dmAdView.frame = CGRectMake(0, 366, 
                                          DOMOB_AD_SIZE_320x50.width,
                                          DOMOB_AD_SIZE_320x50.height);    
             
             NSLog(@"_dmAdView inited");
         }
         NSLog(@"%@",_dmAdView);
         _dmAdView.delegate = self; // 设置 Delegate
         _dmAdView.rootViewController = self; // 设置 RootViewController
         [self.view addSubview:_dmAdView]; // 将广告视图添加到父视图中
         [_dmAdView loadAd]; // 开   始加载广告
         
         // 检查更新提醒，此处使用的是测试ID，请登陆多盟官网（www.domob.cn）获取新的ID 
         DMTools *_dmTools = [[DMTools alloc] initWithPublisherId:DOMOB_AD_KEY];
         [_dmTools checkRateInfo];
     
     }
     */
    self.tableData = [DataService DicBooksList];
    
 
//    self.title=[NSString stringWithFormat:@"%@",BookTitle];
    self.title = @"家庭生活必备图书合集";
    
  
    self.tableView.backgroundColor=[UIColor clearColor];
      self.tableView.alpha = 0.8;
    self.tableView.separatorColor=[UIColor clearColor];
    self.tableView.dataSource=self;
    
    [self.tableView reloadData];
 
}

- (void)viewDidUnload
{
    [self setTableView:nil];
    [self setBackImage:nil];
//    _dmAdView=nil;
    [super viewDidUnload];

}
-(void) viewDidDisappear:(BOOL)animated
{
    self.tableData=nil;
    [self viewDidUnload];
    
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
 // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count =self.tableData.count;
    double result =  count;
   
    // Return the number of rows in the section.
    return result;
}
- (NSComparisonResult)compareKey:(NSString *)p
{
    return [self.description compare:p];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    // UITableViewCell *cell = [tableView  dequeueReusableCellWithIdentifier:CellIdentifier];
        // Configure the cell...
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
    cell.backgroundColor = [UIColor clearColor];
    
     //排序 
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    NSArray * keys= self.tableData.allKeys;
   SEL sel = @selector(compare:);
    //横栏 
   NSBundle * mainBundle = [NSBundle mainBundle];
    NSString *bannerPath=[mainBundle  pathForAuxiliaryExecutable:@"bg_single.png"];
    
    UIImage * bannerimage =[UIImage imageWithContentsOfFile:bannerPath];
    CGRect  rectImage =  CGRectMake(7, 124, 306, 22);
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:rectImage];
    
    imageview.image=bannerimage;
     [cell addSubview:imageview];   
    
    
    keys= [keys sortedArrayUsingSelector:sel];
    
       NSInteger dataIndex = (indexPath.row);
    
   
            //获得数据
            NSString * strKey =[keys objectAtIndex:dataIndex];
            NSDictionary * dicData =[self.tableData objectForKey:strKey];
            //填充控件
           
            NSString *coverPath=[mainBundle  pathForAuxiliaryExecutable:[dicData objectForKey:Cover]];
            
            UIImage *image =[UIImage imageWithContentsOfFile:coverPath];
            CGRect  rectimage =  CGRectMake(30, 18, 80, 110);
            
            
            
            UIButton *btnImage = [[UIButton alloc] initWithFrame:rectimage ];
            
            [btnImage setBackgroundImage:image forState:UIControlStateNormal];
            
            [btnImage addTarget:self action:@selector(onBookClick:) forControlEvents:UIControlEventTouchUpInside];
            
            
            [btnImage setTag: [strKey integerValue]];
            
            [cell addSubview:btnImage];   
            
    //标题 
  
     NSString * strTitle =[dicData objectForKey:Title];
     CGRect  rectTitle =  CGRectMake(120, 30, 200, 100);
     UILabel *lblTitle = [[UILabel alloc] initWithFrame:rectTitle];
     lblTitle.numberOfLines=3;
     
     lblTitle.text =[strTitle stringByReplacingOccurrencesOfString:@"." withString:@"\n"];
     [lblTitle setBackgroundColor:[UIColor clearColor]];
     lblTitle.textColor =[UIColor blackColor];
     lblTitle.font =[UIFont  fontWithName:@"LiSu" size:23];
     
     [cell addSubview:lblTitle];   
      
       
    /*
    NSInteger dataIndex = (indexPath.row);
    
 
            //获得数据
        NSString * strKey =[keys objectAtIndex:dataIndex];
    
    NSLog(@"%@-%d",strKey,dataIndex);
    
            NSDictionary * dicData =[self.tableData objectForKey:strKey];
            //填充控件
            NSBundle * mainBundle = [NSBundle mainBundle];
            NSString *coverPath=[mainBundle  pathForAuxiliaryExecutable:[dicData objectForKey:Cover]];
       
            UIImage *image =[UIImage imageWithContentsOfFile:coverPath];
            CGRect  rect =  CGRectMake(16, 28, 80, 100);
            
            
            
            UIButton *btnImage = [[UIButton alloc] initWithFrame:rect ];
            
            [btnImage setBackgroundImage:image forState:UIControlStateNormal];
            
            [btnImage addTarget:self action:@selector(onBookClick:) forControlEvents:UIControlEventTouchUpInside];
            
           
           [btnImage setTag: [strKey integerValue]];
            
            [cell addSubview:btnImage];   
     */
    //标题 
    /*
        NSString * strTitle =[dicData objectForKey:Title];
    CGRect  rectTitle =  CGRectMake(120, 30, 200, 100);
    UILabel *lblTitle = [[UILabel alloc] initWithFrame:rectTitle];
    lblTitle.numberOfLines=3;
    
    lblTitle.text =[strTitle stringByReplacingOccurrencesOfString:@"." withString:@"\n"];
    [lblTitle setBackgroundColor:[UIColor clearColor]];
    lblTitle.textColor =[UIColor blackColor];
    lblTitle.font =[UIFont  fontWithName:@"LiSu" size:23];
    
    [cell addSubview:lblTitle];   
    */
    return cell;
}
  
-(void) onBookClick:(id)sender
{
        NSLog(@"%d",[sender tag]);
    
    
        [DataService SetBookKey:[NSString stringWithFormat:@"%d",[sender tag]]];
    
        [self performSegueWithIdentifier:@"sgPushDetails" sender:self];

    
 
    


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}

// 成功加载广告后，回调该方法
- (void)dmAdViewSuccessToLoadAd:(DMAdView *)adView
{
    self.tableView.frame=CGRectMake(0, 0,  320,366);    
    NSLog(@"[Domob Sample] success to load ad.");
}

// 加载广告失败后，回调该方法
- (void)dmAdViewFailToLoadAd:(DMAdView *)adView withError:(NSError *)error
{
    NSLog(@"[Domob Sample] fail to load ad. %@", error);    
}
 */
/*
// 当将要呈现出 Modal View 时，回调该方法。如打开内置浏览器。
- (void)dmWillPresentModalViewFromAd:(DMAdView *)adView
{
    NSLog(@"[Domob Sample] will present modal view.");    
}

// 当呈现的 Modal View 被关闭后，回调该方法。如内置浏览器被关闭。
- (void)dmDidDismissModalViewFromAd:(DMAdView *)adView
{
    NSLog(@"[Domob Sample] did dismiss modal view.");
}

// 当因用户的操作（如点击下载类广告，需要跳转到Store），需要离开当前应用时，回调该方法
- (void)dmApplicationWillEnterBackgroundFromAd:(DMAdView *)adView
{
    NSLog(@"[Domob Sample] will enter background.");    
}
#pragma mark - Table view delegate
//表格选择控件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     
    NSArray * keys= self.tableData.allKeys;
    SEL sel = @selector(compare:);
    keys= [keys sortedArrayUsingSelector:sel];
    
    NSInteger dataIndex = (indexPath.row);
    
    
    //获得数据
    NSString * strKey =[keys objectAtIndex:dataIndex];
 
    
    [DataService SetBookKey:strKey];
    
    [self performSegueWithIdentifier:@"sgPushDetails" sender:self];
    
    
    
    
    // Navigation logic may go here. Create and push another view controller.
    /*
   BookDetailsViewController *detailViewController =[self.storyboard instantiateViewControllerWithIdentifier:@"BookDetailsViewController"];    
    detailViewController.title=@"sadfasdf";
   // BookDetailsViewController * detailViewController=[[BookDetailsViewController alloc] initWithNibName:@"BookDetailsViewController" bundle:nil];
   
    NSLog(@"%@",detailViewController);
     
    // ...
     // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
     */
    
}
- (IBAction)tapBookCity:(id)sender {
    
    BookCityViewController* bookCityVC = [[BookCityViewController alloc]init];
    [self presentViewController:bookCityVC animated:YES completion:nil];
}

@end
